﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using ArchivingDataModel;
using ArchivingDataModel.Enums;
using ArchivingDataWebForms.Helpers;
using Telerik.Web.UI;
using System.Linq.Dynamic;
using TelerikHelper;

namespace ArchivingDataWebForms.Pages.Files
{
    public partial class AddFile : ArchivingDataWebForms.Helpers.WebFormBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (!this.IsPostBack)
                    {
                        //exsisting file bind controls
                        if (!string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.File_ID]))
                        {
                            this.serverTitle.InnerText= "تعديل ملف";
                            long id = Convert.ToInt64(this.Request.QueryString[QueryStringParams.File_ID]);
                            ArchivingDataModel.File file = ent.Files.FirstOrDefault(i => i.File_ID == id);
                            this.RadTextBoxCode.Text = file.File_Code;
                            this.RadTextBoxTitle.Text = file.FileTitle_Ar;
                            this.RadTextBoxSubject.Text = file.FileSubject_Ar;
                            this.RadTextBoxNote.Text = file.FileNote_Ar;
                            this.AdvancedDateTimePickerFrom.SelectedDate = file.FromDate;
                            this.AdvancedDateTimePickerTo.SelectedDate = file.ToDate;
                            this.RadButtonRecycleBin.Checked = file.Is_RecycleBin == true;
                        }
                        else
                        {
                            this.AdvancedRadGridResults.Visible = false;
                        }
                    }
                    this.createCustomFields();
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("لقد حدث الخطأ التالي " + er.ToString(), NotificationIconType.Error);
            }
        }

        protected void RadButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    //insert
                    ArchivingDataModel.File file = null;
                    if (string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.File_ID]))
                    {
                        //check for folder
                        if (!string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.Folder_ID]))
                        {
                            long id = Convert.ToInt64(this.Request.QueryString[QueryStringParams.Folder_ID]);
                            file = new ArchivingDataModel.File()
                            {
                                Folder = ent.Folders.FirstOrDefault(i => i.Folder_ID == id),
                                File_Code = this.RadTextBoxCode.Text,
                                File_Order = ent.Folders.FirstOrDefault(i => i.Folder_ID == id).Files.Count() + 1,
                                FileTitle_Ar = this.RadTextBoxTitle.Text,
                                FileTitle_En = "",
                                FileSubject_Ar = this.RadTextBoxSubject.Text,
                                FileSubject_En = "",
                                FileNote_Ar = this.RadTextBoxNote.Text,
                                FileNote_En = "",
                                FromDate = this.AdvancedDateTimePickerFrom.SelectedDate,
                                ToDate = this.AdvancedDateTimePickerTo.SelectedDate,
                                Is_RecycleBin = this.RadButtonRecycleBin.Checked
                            };
                            file.File_UniqueText = WebHelper.Helpers.StringHelper.ToUniqueStatement(file.File_Code + file.FileTitle_Ar + file.FileTitle_En + file.FileSubject_Ar + file.FileSubject_En + file.FileNote_Ar + file.FileNote_En);
                            ent.AddToFiles(file);
                            this.getvaluesFromCustomFields(ent,file);
                            ent.SaveChanges();
                            this.ShowNotification("لقد تم الحفظ", NotificationIconType.Ok);
                            string url = WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Files/AddFile.aspx?" + QueryStringParams.File_ID + "=" + file.File_ID);
                            this.Redirect(url, 1000);
                        }
                    }
                    //update 
                    else
                    {
                        long id = Convert.ToInt64(this.Request.QueryString[QueryStringParams.File_ID]);
                        file = ent.Files.FirstOrDefault(i => i.File_ID == id);
                        //file.File_Code = this.RadTextBoxCode.Text;
                        //file.FileTitle_Ar = this.RadTextBoxTitle.Text;
                        //file.FileTitle_En = "";
                        //file.FileSubject_Ar = this.RadTextBoxSubject.Text;
                        //file.FileSubject_En = "";
                        //file.FileNote_Ar = this.RadTextBoxNote.Text;
                        //file.FileNote_En = "";
                        //file.FromDate = this.AdvancedDateTimePickerFrom.SelectedDate;
                        //file.ToDate = this.AdvancedDateTimePickerTo.SelectedDate;
                        //file.Is_RecycleBin = this.RadButtonRecycleBin.Checked;
                        //file.File_UniqueText = WebHelper.Helpers.StringHelper.ToUniqueStatement(file.File_Code + file.FileTitle_Ar + file.FileTitle_En + file.FileSubject_Ar + file.FileSubject_En + file.FileNote_Ar + file.FileNote_En);
                        this.getvaluesFromCustomFields(ent,file);
                        ent.SaveChanges();
                        this.ShowNotification("لقد تم الحفظ", NotificationIconType.Ok);
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطاء التالي اثناء الحفظ" + er.Message, NotificationIconType.Error);
                return;
            }
        }
        protected void AdvancedRadGridResults_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    Attachment[] items = new Attachment[] { };
                    if (!e.IsFromDetailTable)
                    {
                        if (!string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.File_ID]))
                        {
                            long id = Convert.ToInt64(this.Request.QueryString[QueryStringParams.File_ID]);
                            items = ent.Attachments.Where(i => i.File.File_ID == id).ToArray();
                            this.AdvancedRadGridResults.DataSource = items;
                        }
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي " + er.Message, NotificationIconType.Error);
                //e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_DetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    GridDataItem dataItem = (GridDataItem)e.DetailTableView.ParentItem;
                    if (e.DetailTableView.Name == "AttachmentsVersioning")
                    {
                        long id = Convert.ToInt64(dataItem.GetDataKeyValue("Attachment_ID"));
                        var attachmentversioning = ent.AttachmentsVersionings.Where(i => i.Attachment.Attachment_ID == id).Select(i => new { i.Version_ID, i.Version_Date, Attachment_ID = i.Attachment.Attachment_ID, i.Attachment_Code, i.AttachmentNote_Ar, i.AttachmentTitle_Ar, i.Version_Path, i.OCR }).OrderByDescending(i => i.Version_ID).ToArray();
                        e.DetailTableView.DataSource = attachmentversioning;
                    }
                    else if (e.DetailTableView.Name == "master")
                    {
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي " + er.Message, NotificationIconType.Error);
                //e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_ItemCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (e.CommandName.ToLower() == "DownlodAttachment".ToLower())
                    {
                        long id = Convert.ToInt64(e.CommandArgument);
                        this.iframeDownload.Attributes["src"] = WebHelper.Helpers.UrlHelper.GetCompleteUri(ent.Attachments.FirstOrDefault(i => i.Attachment_ID == id).Attachment_Path);
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }

        }
        protected void AdvancedRadGridResults_InsertCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    GridEditableItem editedItem = e.Item as GridEditableItem;
                    if (e.Item.OwnerTableView.Name == "master")
                    {
                        if (!string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.File_ID]))
                        {
                            RadAsyncUpload radAU = (RadAsyncUpload)e.Item.FindControl("RadAsyncUploadAttachment");
                            if (radAU.UploadedFiles.Count > 0)
                            {
                                long id = Convert.ToInt64(this.Request.QueryString[QueryStringParams.File_ID]);
                                Hashtable newValues = new Hashtable();
                                e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                                string code = newValues["Attachment_Code"].ToString();
                                string titleAr = newValues["AttachmentTitle_Ar"].ToString();
                                string noteAr = newValues["AttachmentNote_Ar"].ToString();
                                string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + titleAr + noteAr);
                                int order = ent.Files.FirstOrDefault(i => i.File_ID == id).Attachments.Count() + 1;
                                Attachment item = new Attachment
                                {
                                    Attachment_Order = order,
                                    Attachment_Code = code,
                                    AttachmentTitle_Ar = titleAr,
                                    AttachmentNote_Ar = noteAr,
                                    Attachment_UniqueText = uniquetext
                                };
                                ent.Files.FirstOrDefault(i => i.File_ID == id).Attachments.Add(item);
                                ent.SaveChanges();
                                string imagePath = CustomAppSettings.DefaultFileImagePath;
                                string datePath = DateTime.Now.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
                                imagePath = CustomAppSettings.FilesPathes + "/" + datePath + "/" + item.Attachment_ID + radAU.UploadedFiles[0].GetExtension();
                                Directory.CreateDirectory(Path.GetDirectoryName(CustomAppSettings.getActualPath(imagePath)));
                                radAU.UploadedFiles[0].SaveAs(CustomAppSettings.getActualPath(imagePath));

                                item.Attachment_Path = imagePath;
                                item.MimeType = radAU.UploadedFiles[0].ContentType;
                                if (item.MimeType == null)
                                {
                                   item.MimeType = WebHelper.Helpers.MimeTypeHelper.getMimeFromExtension(radAU.UploadedFiles[0].GetExtension());
                                   if (item.MimeType == null)
                                   {
                                       item.MimeType = WebHelper.Helpers.MimeTypeHelper.getMimeFromFile(CustomAppSettings.getActualPath(imagePath));
                                   }
                                }
                                ent.SaveChanges();
                                this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                            }
                            else
                            {
                                this.ShowNotification("من فضلك قم بتحميل احد الملفات", NotificationIconType.Ok);
                            }
                        }
                    }
                    else if (e.Item.OwnerTableView.Name == "master")
                    {
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحفظ " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    GridEditableItem editedItem = e.Item as GridEditableItem;
                    if (e.Item.OwnerTableView.Name == "master")
                    {
                        Hashtable newValues = new Hashtable();
                        e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                        long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Attachment_ID"]);
                        var item = ent.Attachments.FirstOrDefault(i => i.Attachment_ID == id);
                        item.FileReference.Load();
                        RadAsyncUpload radAU = (RadAsyncUpload)e.Item.FindControl("RadAsyncUploadAttachment");
                        if (radAU.UploadedFiles.Count > 0)
                        {
                            //add versioning
                            AttachmentsVersioning versioning = new AttachmentsVersioning
                            {
                                Version_Date = DateTime.Now,
                                Attachment_Code = item.Attachment_Code,
                                Attachment_Order = item.Attachment_Order,
                                Attachment_UniqueText = item.Attachment_UniqueText,
                                AttachmentNote_Ar = item.AttachmentNote_Ar,
                                AttachmentNote_En = item.AttachmentNote_En,
                                AttachmentTitle_Ar = item.AttachmentTitle_Ar,
                                AttachmentTitle_En = item.AttachmentTitle_En,
                                Customer_ID = item.Customer_ID,
                                File_ID = item.File.File_ID,
                                IS_Encrypted = item.IS_Encrypted,
                                MimeType = item.MimeType,
                                OCR = item.Ocr,
                            };
                            item.AttachmentsVersionings.Add(versioning);
                            ent.SaveChanges();
                            string datePath = DateTime.Now.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
                            string versionPath = CustomAppSettings.AttachmentsVersioning + "/" + datePath + "/" + versioning.Version_ID + Path.GetExtension(CustomAppSettings.getActualPath(item.Attachment_Path));
                            Directory.CreateDirectory(Path.GetDirectoryName(CustomAppSettings.getActualPath(versionPath)));
                            System.IO.File.Copy(CustomAppSettings.getActualPath(item.Attachment_Path), CustomAppSettings.getActualPath(versionPath));
                            versioning.Version_Path = versionPath;

                            string imagePath = CustomAppSettings.FilesPathes + "/" + datePath + "/" + item.Attachment_ID + radAU.UploadedFiles[0].GetExtension();
                            Directory.CreateDirectory(Path.GetDirectoryName(CustomAppSettings.getActualPath(imagePath)));
                            radAU.UploadedFiles[0].SaveAs(CustomAppSettings.getActualPath(imagePath));
                            item.Attachment_Path = imagePath;
                            item.MimeType = radAU.UploadedFiles[0].ContentType;
                            
                            if (item.MimeType == null)
                            {
                                item.MimeType = WebHelper.Helpers.MimeTypeHelper.getMimeFromExtension(radAU.UploadedFiles[0].GetExtension());
                                if (item.MimeType == null)
                                {
                                    item.MimeType = WebHelper.Helpers.MimeTypeHelper.getMimeFromFile(CustomAppSettings.getActualPath(imagePath));
                                }
                            }
                        }
                        string code = newValues["Attachment_Code"].ToString();
                        string titleAr = newValues["AttachmentTitle_Ar"].ToString();
                        string noteAr = newValues["AttachmentNote_Ar"].ToString();
                        string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + titleAr + noteAr);

                        item.Attachment_Code = code;
                        item.AttachmentTitle_Ar = titleAr;
                        item.AttachmentNote_Ar = noteAr;
                        item.Attachment_UniqueText = uniquetext;
                        ent.SaveChanges();
                        this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                    }
                    else if (e.Item.OwnerTableView.Name == "master")
                    {

                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحفظ " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (e.Item.OwnerTableView.Name == "master")
                    {
                        long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["FileType_ID"]);
                        ent.DeleteObject(ent.FilesTypes.FirstOrDefault(i => i.FileType_ID == id));
                        ent.SaveChanges();
                        this.ShowNotification("تم الحذف بنجاح", NotificationIconType.Ok);
                    }
                    else if (e.Item.OwnerTableView.Name == "master")
                    {
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحذف " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_ItemDataBound(object sender, GridItemEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (e.Item is GridEditableItem && e.Item.IsInEditMode)
                    {
                        GridEditableItem editedItem = e.Item as GridEditableItem;
                        if (e.Item.OwnerTableView.Name == "CustomFields")
                        {
                            RadDropDownList rDDLCFieldType = (RadDropDownList)editedItem.FindControl("RadDropDownListCFieldType");
                            if (rDDLCFieldType != null)
                            {
                                var items = ent.CusFieldsTypes.ToArray();
                                rDDLCFieldType.DataSource = items;
                                rDDLCFieldType.DataTextField = "CFieldTypeName_Ar";
                                rDDLCFieldType.DataValueField = "CFieldType_ID";
                                if (items.Count() > 0)
                                {
                                    rDDLCFieldType.SelectedIndex = 0;
                                }
                                rDDLCFieldType.DataBind();

                                RadDropDownList rDDLCusField = (RadDropDownList)editedItem.FindControl("RadDropDownListCusField");
                                if (rDDLCusField != null)
                                {
                                    long id = Convert.ToInt64(rDDLCFieldType.SelectedValue);
                                    long FileTypeID = Convert.ToInt64(editedItem.OwnerTableView.ParentItem.GetDataKeyValue("FileType_ID"));
                                    var currentIDs = ent.FilesTypes_CusFields.Where(i => i.FilesType.FileType_ID == id).Select(i => i.CusField.CusField_ID).ToList();
                                    var CusFieldsitems = ent.CusFields.Where(i => i.CusFieldsType.CFieldType_ID == id).ToArray().Where(i => !currentIDs.Contains(i.CusField_ID));
                                    rDDLCusField.DataSource = CusFieldsitems;
                                    rDDLCusField.DataTextField = "CusFieldName";
                                    rDDLCusField.DataValueField = "CusField_ID";
                                    if (CusFieldsitems.Count() > 0)
                                    {
                                        rDDLCusField.SelectedIndex = 0;
                                    }
                                    rDDLCusField.DataBind();
                                }
                            }
                        }
                        else if (e.Item.OwnerTableView.Name == "master")
                        {
                        }
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridFilteringItem)
            {
                GridFilteringItem filteringItem = e.Item as GridFilteringItem;
                //set dimensions for the filter textbox  
                TextBox box = filteringItem["Attachment_Code"].Controls[0] as TextBox;
                TextBox box1 = filteringItem["AttachmentTitle_Ar"].Controls[0] as TextBox;
                TextBox box2 = filteringItem["AttachmentNote_Ar"].Controls[0] as TextBox;
                TextBox box3 = filteringItem["Ocr"].Controls[0] as TextBox;
                
                box.Width = Unit.Pixel(50);
                box1.Width = Unit.Pixel(100);
                box2.Width = Unit.Pixel(100);
                box3.Width = Unit.Pixel(150);
            }
        }


        private void createCustomFields()
        {
            using (ArchivingDataEntities ent = new ArchivingDataEntities())
            {
                FilesType ft = null;
                ArchivingDataModel.File file = null;
                if (!string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.Folder_ID]))
                {
                    long id = Convert.ToInt64(this.Request.QueryString[QueryStringParams.Folder_ID]);
                    Folder folder = ent.Folders.FirstOrDefault(i => i.Folder_ID == id);
                    folder.FilesTypeReference.Load();
                    ft = folder.FilesType;
                }
                else if (!string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.File_ID]))
                {
                    long id = Convert.ToInt64(this.Request.QueryString[QueryStringParams.File_ID]);
                    file = ent.Files.FirstOrDefault(i => i.File_ID == id);
                    file.FolderReference.Load();
                    Folder folder = file.Folder;
                    folder.FilesTypeReference.Load();
                    ft = folder.FilesType;
                }
                if (ft != null)
                {
                    ft.FilesTypes_CusFields.Load();
                    var ftCusFields = ft.FilesTypes_CusFields.OrderBy(i => i.CusField_Order).ToArray();
                    HtmlGenericControl Ulist = new HtmlGenericControl("ul");
                    Ulist.Attributes["class"] = "UlLayout";
                    foreach (var item in ftCusFields)
                    {
                        item.CusFieldReference.Load();
                        item.CusField.CusFieldsTypeReference.Load();
                        
                        //label
                        HtmlGenericControl lilabel = new HtmlGenericControl("li");
                        lilabel.Attributes.Add("class", "paddingTop");
                        lilabel.InnerText = item.CusFieldLabel_Ar;
                        Ulist.Controls.Add(lilabel);

                        
                        //control
                        HtmlGenericControl liControl = new HtmlGenericControl("li");
                        liControl.Attributes["class"] = "normalFlow";
                        if (item.CusField.CusFieldsType.CFieldType_ID == (long)CustomFieldTypeEnum.Text)
                        {
                            RadTextBox control = new RadTextBox();
                            control.Rows = 2;
                            control.TextMode = InputMode.MultiLine;
                            control.ID = item.CusField.CusFieldName;
                            control.SkinID = "RadTextBoxDefault";
                            liControl.Controls.Add(control);
                            if (!this.IsPostBack && file != null)
                            {
                                var value = file.GetType().GetProperty(item.CusField.CusFieldName).GetValue(file, null);
                                if (value != null)
                                {
                                    control.Text = value.ToString();
                                }
                            }
                            Ulist.Controls.Add(liControl);


                            //RegularExpressionsvalidationControl
                            if (!string.IsNullOrEmpty(item.RegExp_AR))
                            {
                                HtmlGenericControl liValidator = new HtmlGenericControl("li");
                                liValidator.Attributes["class"] = "normalFlow";
                                RegularExpressionValidator validator = new RegularExpressionValidator();
                                validator.ID = "vR" + item.CusField.CusFieldName;
                                validator.ControlToValidate = item.CusField.CusFieldName;
                                validator.ErrorMessage = item.RegExpMessage_AR;
                                validator.ValidationExpression = item.RegExp_AR;
                                validator.SkinID = "RequiredFieldValidatorDefault";
                                liValidator.Controls.Add(validator);
                                Ulist.Controls.Add(liValidator);
                            }
                            //RequiredvalidationControl
                            if (!string.IsNullOrEmpty(item.RequiredMessage_AR))
                            {
                                HtmlGenericControl liValidator = new HtmlGenericControl("li");
                                liValidator.Attributes["class"] = "normalFlow";
                                RequiredFieldValidator validator = new RequiredFieldValidator();
                                validator.ID = "v" + item.CusField.CusFieldName;
                                validator.ControlToValidate = item.CusField.CusFieldName;
                                validator.ErrorMessage = item.RequiredMessage_AR;
                                validator.SkinID = "RequiredFieldValidatorDefault";
                                liValidator.Controls.Add(validator);
                                Ulist.Controls.Add(liValidator);
                            }
                        }
                        else if (item.CusField.CusFieldsType.CFieldType_ID == (long)CustomFieldTypeEnum.Number)
                        {
                            RadNumericTextBox control = new RadNumericTextBox();
                            control.ID = item.CusField.CusFieldName;
                            control.SkinID = "RadNumericTextBoxDefault";
                            control.NumberFormat.DecimalDigits = item.NumberDecimalPlaces.HasValue ? Convert.ToInt32(item.NumberDecimalPlaces.Value) : 0;
                            control.MinValue = item.NumberMinValue.HasValue ? Convert.ToDouble(item.NumberMinValue.Value) : double.MinValue;
                            control.MaxValue = item.NumberMaxValue.HasValue ? Convert.ToDouble(item.NumberMaxValue.Value) : double.MaxValue;
                            liControl.Controls.Add(control);
                            if (!this.IsPostBack && file != null)
                            {
                                var value = file.GetType().GetProperty(item.CusField.CusFieldName).GetValue(file, null);
                                if (value != null)
                                {
                                    control.Text = value.ToString();
                                }
                            }
                            Ulist.Controls.Add(liControl);

                            //RequiredvalidationControl
                            if (!string.IsNullOrEmpty(item.RequiredMessage_AR))
                            {
                                HtmlGenericControl liValidator = new HtmlGenericControl("li");
                                liValidator.Attributes["class"] = "normalFlow";
                                RequiredFieldValidator validator = new RequiredFieldValidator();
                                validator.ID = "v" + item.CusField.CusFieldName;
                                validator.ControlToValidate = item.CusField.CusFieldName;
                                validator.ErrorMessage = item.RequiredMessage_AR;
                                validator.SkinID = "RequiredFieldValidatorDefault";
                                liValidator.Controls.Add(validator);
                                Ulist.Controls.Add(liValidator);
                            }
                        }
                        else if (item.CusField.CusFieldsType.CFieldType_ID == (long)CustomFieldTypeEnum.Date)
                        {
                            AdvancedDateTimePicker control = new AdvancedDateTimePicker();
                            control.ID = item.CusField.CusFieldName;
                            control.SkinID = "AdvancedDateTimePickerDefault";
                            control.MinDate = item.DateMinValue.HasValue ? item.DateMinValue.Value : DateTime.MinValue;
                            control.MaxDate = item.DateMaxValue.HasValue ? item.DateMaxValue.Value : DateTime.MaxValue;
                            liControl.Controls.Add(control);
                            if (!this.IsPostBack && file != null)
                            {
                                control.SelectedDate = (DateTime?)file.GetType().GetProperty(item.CusField.CusFieldName).GetValue(file, null);
                            }
                            Ulist.Controls.Add(liControl);



                            //RequiredvalidationControl
                            if (!string.IsNullOrEmpty(item.RequiredMessage_AR))
                            {
                                HtmlGenericControl liValidator = new HtmlGenericControl("li");
                                liValidator.Attributes["class"] = "normalFlow";
                                RequiredFieldValidator validator = new RequiredFieldValidator();
                                validator.ID = "v" + item.CusField.CusFieldName;
                                validator.ControlToValidate = item.CusField.CusFieldName;
                                validator.ErrorMessage = item.RequiredMessage_AR;
                                validator.SkinID = "RequiredFieldValidatorDefault";
                                liValidator.Controls.Add(validator);
                                Ulist.Controls.Add(liValidator);
                            }
                        }
                        else if (item.CusField.CusFieldsType.CFieldType_ID == (long)CustomFieldTypeEnum.Boolean)
                        {

                            //only for checkbox
                            Ulist.Controls.Remove(lilabel);
                            liControl.Attributes.Add("class", "paddingTop");


                            RadButton control = new RadButton();
                            control.ToggleType = ButtonToggleType.CheckBox;
                            control.ButtonType = RadButtonType.ToggleButton;
                            control.Text = item.CusFieldLabel_Ar;
                            control.ID = item.CusField.CusFieldName;
                            control.AutoPostBack = false;
                            liControl.Controls.Add(control);
                            if (!this.IsPostBack && file != null)
                            {
                                var value = file.GetType().GetProperty(item.CusField.CusFieldName).GetValue(file, null);
                                if (value != null)
                                {
                                    control.Checked = bool.Parse(file.GetType().GetProperty(item.CusField.CusFieldName).GetValue(file, null).ToString());
                                }
                            }
                            Ulist.Controls.Add(liControl);
                        }
                        else if (item.CusField.CusFieldsType.CFieldType_ID == (long)CustomFieldTypeEnum.ChooseFromList)
                        {
                            item.PreValues.Load();
                            var values = item.PreValues.ToArray();
                            RadDropDownList control = new RadDropDownList();
                            control.ID = item.CusField.CusFieldName;
                            control.DataSource = values;
                            control.DataTextField = "PreValueName_Ar";
                            control.DataValueField = "PreValue_ID";
                            control.DataBind();
                            control.Height = 40;
                            control.SkinID = "RadDropDownListDefault";
                            control.AutoPostBack = false;
                            liControl.Controls.Add(control);
                            if (!this.IsPostBack)
                            {
                                if (file != null)
                                {
                                    var selected=file.GetType().GetProperty(item.CusField.CusFieldName).GetValue(file, null);
                                    if (selected != null)
                                    {
                                        control.SelectedValue = selected.ToString();
                                    }
                                }
                                else
                                {
                                    var selected=values.FirstOrDefault(i => i.IsSelected == true);
                                    if(selected!=null)
                                    {
                                        control.SelectedValue = selected.PreValue_ID.ToString();
                                    }
                                }
                            }
                            Ulist.Controls.Add(liControl);
                            //RequiredvalidationControl
                            if (!string.IsNullOrEmpty(item.RequiredMessage_AR))
                            {
                                HtmlGenericControl liValidator = new HtmlGenericControl("li");
                                liValidator.Attributes["class"] = "normalFlow";
                                RequiredFieldValidator validator = new RequiredFieldValidator();
                                validator.ID = "v" + item.CusField.CusFieldName;
                                validator.ControlToValidate = item.CusField.CusFieldName;
                                validator.ErrorMessage = item.RequiredMessage_AR;
                                validator.SkinID = "RequiredFieldValidatorDefault";
                                liValidator.Controls.Add(validator);
                                Ulist.Controls.Add(liValidator);
                            }
                        }
                        else if (item.CusField.CusFieldsType.CFieldType_ID == (long)CustomFieldTypeEnum.MultiChoise)
                        {
                            item.PreValues.Load();
                            var values = item.PreValues.ToArray();
                            RadListBox control = new RadListBox();
                            control.CheckBoxes = true;
                            control.SelectionMode = ListBoxSelectionMode.Multiple;
                            control.ID = item.CusField.CusFieldName;
                            control.DataSource = values;
                            control.DataTextField = "PreValueName_Ar";
                            control.DataValueField = "PreValue_ID";
                            control.DataBind();
                            control.SkinID = "RadListBoxDefault";
                            liControl.Controls.Add(control);
                            if (!this.IsPostBack)
                            {
                                for (int i = 0; i < control.Items.Count; i++)
                                {
                                    if (file != null)
                                    {
                                        var value = file.GetType().GetProperty(item.CusField.CusFieldName).GetValue(file, null);
                                        if (value != null)
                                        {
                                            string[] checkedItems = file.GetType().GetProperty(item.CusField.CusFieldName).GetValue(file, null).ToString().Split(',');
                                            if (checkedItems.Contains(control.Items[i].Value))
                                            {
                                                control.Items[i].Checked = true;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        var selected=values.FirstOrDefault(k => k.PreValue_ID.ToString() == control.Items[i].Value);
                                        if(selected!=null)
                                        {
                                            control.Items[i].Checked = selected.IsSelected == true;
                                        }
                                    }
                                }
                            }
                            Ulist.Controls.Add(liControl);
                        }
                        //clear
                        HtmlGenericControl liClear = new HtmlGenericControl("li");
                        liClear.Attributes["class"] = "clear";
                        Ulist.Controls.Add(liClear);
                        this.PanelCustomfields.Controls.Add(Ulist);
                    }
                }
            }
        }
        private void getvaluesFromCustomFields(ArchivingDataEntities ent, ArchivingDataModel.File file)
        {
            if (file.Folder == null)
            {
                file.FolderReference.Load();
            }
            Folder folder = file.Folder;
            folder.FilesTypeReference.Load();
            FilesType ft = folder.FilesType;
            if (ft != null)
            {
                ft.FilesTypes_CusFields.Load();
                var ftCusFields = ft.FilesTypes_CusFields.OrderBy(i => i.CusField_Order).ToArray();
                foreach (var item in ftCusFields)
                {
                    item.CusFieldReference.Load();
                    item.CusField.CusFieldsTypeReference.Load();
                    if (item.CusField.CusFieldsType.CFieldType_ID == (long)CustomFieldTypeEnum.Text)
                    {
                        RadTextBox control = (RadTextBox)this.PanelCustomfields.FindControl(item.CusField.CusFieldName);
                        file.GetType().GetProperty(item.CusField.CusFieldName).SetValue(file, control.Text, null);
                    }
                    else if (item.CusField.CusFieldsType.CFieldType_ID == (long)CustomFieldTypeEnum.Date)
                    {
                        AdvancedDateTimePicker control = (AdvancedDateTimePicker)this.PanelCustomfields.FindControl(item.CusField.CusFieldName);
                        if (control.SelectedDate.HasValue)
                        {
                            file.GetType().GetProperty(item.CusField.CusFieldName).SetValue(file, control.SelectedDate.Value, null);
                        }
                    }
                    else if (item.CusField.CusFieldsType.CFieldType_ID == (long)CustomFieldTypeEnum.Number)
                    {
                        RadNumericTextBox control = (RadNumericTextBox)this.PanelCustomfields.FindControl(item.CusField.CusFieldName);
                        if (!string.IsNullOrEmpty(control.Text))
                        {
                            file.GetType().GetProperty(item.CusField.CusFieldName).SetValue(file, Convert.ToDecimal(control.Text), null);
                        }
                    }
                    else if (item.CusField.CusFieldsType.CFieldType_ID == (long)CustomFieldTypeEnum.Boolean)
                    {
                        RadButton control = (RadButton)this.PanelCustomfields.FindControl(item.CusField.CusFieldName);
                        file.GetType().GetProperty(item.CusField.CusFieldName).SetValue(file, control.Checked, null);
                    }
                    else if (item.CusField.CusFieldsType.CFieldType_ID == (long)CustomFieldTypeEnum.ChooseFromList)
                    {
                        RadDropDownList control = (RadDropDownList)this.PanelCustomfields.FindControl(item.CusField.CusFieldName);
                        if (control.SelectedValue != null)
                        {
                            file.GetType().GetProperty(item.CusField.CusFieldName).SetValue(file, control.SelectedValue, null);
                        }
                    }
                    else if (item.CusField.CusFieldsType.CFieldType_ID == (long)CustomFieldTypeEnum.MultiChoise)
                    {
                        RadListBox control = (RadListBox)this.PanelCustomfields.FindControl(item.CusField.CusFieldName);
                        string ids = "";
                        for (int i = 0; i < control.Items.Count; i++)
                        {
                            if (control.Items[i].Checked)
                            {
                                if (ids != "")
                                {
                                    ids += ",";
                                }
                                ids += control.Items[i].Value;
                            }
                        }
                        file.GetType().GetProperty(item.CusField.CusFieldName).SetValue(file, ids, null);
                    }

                }
            }
        }

    }
}